import 'dart:async';

import 'package:flutter/cupertino.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_keyboard_visibility/flutter_keyboard_visibility.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:provider/provider.dart';
import 'package:wch/page/home.dart';
import 'package:wch/page/select_hospital.dart';
import 'package:wch/utils/log_utils.dart';
import 'package:wch/utils/time_utils.dart';

import '../constant/config_constant.dart';
import '../constant/event_bus_global.dart';
import '../constant/resource_constant.dart';
import '../constant/text_constant.dart';
import '../helper/event_manager.dart';
import '../helper/preferences_helper.dart';
import '../model/login_custom.dart';
import '../native/net_business.dart';
import '../networking/api.dart';
import '../utils/digital_utils.dart';
import '../utils/loading_utils.dart';
import '../utils/navigator_utils.dart';
import '../utils/toast_utils.dart';
import '../widget/alert_view.dart';
import '../widget/login_widget.dart';
import '../widget/padding_widget.dart';
import '../widget/protocol_widget.dart';
import '../widget/text_widget.dart';
import '../widget/common_widget.dart';
import 'forget_pass.dart';

//
//登录页面
//

class LoginPage extends StatefulWidget {
  const LoginPage({Key? key}) : super(key: key);

  @override
  State<LoginPage> createState() => _LoginPageState();


}

class _LoginPageState extends State<LoginPage> implements EventManagerInterface{
  ///登录实体
  LoginCustomModel loginEntity = LoginCustomModel();
  ///保存切换登录方式前的账号
  String? oldName;
  final String _result = '无';

  bool isShowWechat = false;

  OverlayEntry? entry;

  int clickTimeStamp = 0;
  ///是否已经登录，防止误点击
  bool isLogin = false;

  @override
  void notify(String methodName, Map<dynamic, dynamic> data) {

  }

  @override
  void initState() {
    EventManager.getIns().addObserver(this);

    clickTimeStamp = TimeUtils.getCurrentTimeStamp();
  }


  @override
  void dispose() {
    super.dispose();
    EventManager.getIns().removeObserver(this);
  }

  @override
  Widget build(BuildContext context) {
    return KeyboardDismissOnTap(
      child: ChangeNotifierProvider.value(
          value: loginEntity,
          child: Consumer<LoginCustomModel>(
            builder: (context, model, widget) {
              return KeyboardDismissOnTap(
                child: LoginContainer(
                  child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        const VerPadding(84.0),
                        BigTitleText(LoginText),
                        const VerPadding(76.0),
                        Row(
                          children: [
                            TabRadioWidget(
                              passText,
                              isSelect: model.selectType == 0,
                              callback: () {
                                model.selectType = 0;
                                ///先填充，在保存
                                String? tmpName = model.name;
                                model.name = oldName;
                                model.update();
                                oldName = tmpName;
                                ///通知 输入框切换焦点
                                model.isHideKeyboard = false;
                                globalEventBus.fire(model);
                              },
                            ),
                            HorPadding(40.w),
                            TabRadioWidget(
                              phoneValidText,
                              isSelect: model.selectType == 1,
                              callback: () {
                                model.selectType = 1;
                                ///先填充，在保存
                                String? tmpName = model.name;
                                model.name = oldName;
                                model.update();
                                oldName = tmpName;
                                ///通知 输入框切换焦点
                                model.isHideKeyboard = false;
                                globalEventBus.fire(model);
                              },
                            ),
                          ],
                        ),
                        const VerPadding(40),
                        LoginTypeWidget(
                          width: ScreenUtil().screenWidth * 2 - LoginContainer.horPaddingConstant * 4,
                          loginEntity: model,
                          focusIndex: model.selectType,
                          isSendCodeEnable: isCanSendCode(model),
                        ),
                        const VerPadding(32),
                        CommonBtn(
                          title: LoginText,
                          callback: () {
                            loginLogic(model);
                          },
                          isEnable: isCanLogin(model),
                        ),
                        const VerPadding(20),
                        Row(
                          mainAxisAlignment: MainAxisAlignment.end,
                          children: [
                            GestureDetector(onTap: (){
                              goForgetPass(context);
                            }, child: const F15TitleText(forgetPassText, color: F2TextColor)),
                          ],
                        ),
                        const VerPadding(20),
                        Row(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [
                            GestureDetector(
                              onTap: () {
                                clickProtocol(model);
                              },
                              child: Image.asset(
                                model.isAgree ? loginCheckIcon : loginUncheckIcon,
                                width: 15.0.w,
                                height: 15.0.w,
                              ),
                            ),
                            HorPadding(5.w),
                            Expanded(
                              child: Text.rich(
                                TextSpan(
                                  children: [
                                    TextSpan(
                                      text: iAgreeText,
                                      style: TextStyle(fontSize: 11, color: F2TextColor),
                                    ),
                                    TextSpan(
                                        children: [
                                          TextSpan(
                                            text: userProtocol,
                                            style: TextStyle(fontSize: 11, color: themeColor),
                                            recognizer: TapGestureRecognizer()..onTap = () {
                                              NavigatorUtil.push(
                                                  context, ProtocolWidget(title: userProtocol2, url: agreementUrl,));
                                            }
                                          ),

                                        ],
                                    ),
                                    TextSpan(
                                      text: '与',
                                      style: TextStyle(fontSize: 11, color: F2TextColor),
                                    ),
                                    TextSpan(
                                        children: [
                                          TextSpan(
                                            text: privacyProtocol,
                                            style: TextStyle(fontSize: 11, color: themeColor),
                                            recognizer: TapGestureRecognizer()..onTap = () {
                                              NavigatorUtil.push(
                                                  context, ProtocolWidget(title: privacyProtocol2, url: agreementUrl,));
                                            }
                                          ),
                                        ]
                                    ),
                                  ]
                                )
                              ),
                            )
                            // HorPadding(5.w),
                            // const F11TitleText(
                            //   iAgreeText,
                            //   color: F2TextColor,
                            // ),
                            // GestureDetector(
                            //     onTap: () {
                            //       NavigatorUtil.push(
                            //           context, ProtocolWidget(title: userProtocol2, url: agreementUrl,));
                            //     },
                            //     child:
                            //     const F11TitleText(userProtocol, color: themeColor)),
                            // const F11TitleText('与', color: F2TextColor),
                            // GestureDetector(
                            //     onTap: () {
                            //       NavigatorUtil.push(
                            //           context, ProtocolWidget(title: privacyProtocol2, url: privacyUrl,));
                            //     },
                            //     child: const F11TitleText(privacyProtocol,
                            //         color: themeColor)),
                          ],
                        ),
                        Expanded(child: InkWell(
                          onLongPress: (){
                            entry = OverlayEntry(builder: (ctx){
                              return AlertInputWidget2(title: '设置', hint: '请输入服务器地址', callback: (i, text){
                                baseUrl = text;
                              }, btns: ['确定'], entry: entry!,);
                            });
                            Overlay.of(context).insert(entry!);
                          },
                          child: Container(
                          ))),
                      ]),
                ),
              );
            },
          )),
    );
  }

  ///前往忘记密码页面
  void goForgetPass(BuildContext context) {
    NavigatorUtil.push(context, const ForgetPassPage());
  }
  ///能否点击
  bool isCanLogin(LoginCustomModel model) {
    if (loginEntity.name == null || loginEntity.name!.isEmpty) {
      return false;
    }

    if (loginEntity.selectType == 0) {
      if (loginEntity.pass == null || loginEntity.pass!.isEmpty) {
        return false;
      }
    } else {
      if (loginEntity.code == null || loginEntity.code!.isEmpty) {
        return false;
      }
    }

    return true;
  }

  ///能否发送
  bool isCanSendCode(LoginCustomModel entity) {
    if (loginEntity.name == null || loginEntity.name!.isEmpty) {
      return false;
    }
    if (loginEntity.name!.length < 11) {
      return false;
    }
    if (!DigitalUtils.chinaPhoneNumber(entity.name!)) {
      return false;
    }

    return true;
  }

  void clickProtocol(LoginCustomModel entity) {
    entity.isAgree = !entity.isAgree;
    entity.update();
  }
  ///登录前的判断
  void loginLogic(LoginCustomModel entity) {

    entity.isHideKeyboard = true;
    globalEventBus.fire(entity);
    if (isLogin) {
      return;
    }

    if (!entity.isAgree) {
      ToastUtils.showToast(msg: needSelectProtocol);
      return;
    }
    if(entity.selectType == 0||entity.selectType == 1){
      if (entity.name == null || entity.name!.length < 11) {
        ToastUtils.showToast(msg: checkMobileLen);
        return;
      }

      if (!DigitalUtils.chinaPhoneNumber(entity.name!)) {
        ToastUtils.showToast(msg: checkMobileValid);
        return;
      }

      if (entity.selectType == 0) {
        if (entity.pass == null || entity.pass!.length < 6) {
          ToastUtils.showToast(msg: checkPassValid);
          return;
        }
      } else {
        if (entity.code == null || entity.code!.length != 6) {
          ToastUtils.showToast(msg: checkCodeValid);
          return;
        }
      }
      if (entity.selectType == 0) {
        Loading.getIns().loading(msg: '正在登录中...');
        NetBusiness helper = NetBusiness();
        helper.login(mobile: entity.name!, memberPassword: entity.pass!).then((value) {
          if (value.data != null) {
            PreferencesHelper.setUserToken(value.data!.accessToken!);
            _userIndex(entity.name);
            isLogin = true;
          }
        });
      } else {
        Loading.getIns().loading(msg: '正在登录中...');
        NetBusiness helper = NetBusiness();
        helper.smsLogin(mobile: entity.name!, code: entity.code!).then((value) {
          if (value.data != null) {
            PreferencesHelper.setUserToken(value.data!.accessToken!);
            isLogin = true;
            _userIndex(entity.name);
          }
        });
      }
    }

  }
  ///登录成功之后，调用一次用户信息
  void _userIndex(String? mobile) {
    // NetBusiness().userIndex().then((value) {
    //
    //   if (value.data!.memberMobile != null) {
    //     PreferencesHelper.setMemberMobile(value.data!.memberMobile!);
    //   }
    //   PreferencesHelper.setMemberId(value.data!.id!);
    //   if (value.data!.memberBirthday == null) {
    //     SleepApp.navigatorKey.currentState!
    //         .pushNamedAndRemoveUntil('/userRegisterInfo', (route) => route == null);
    //   } else {
    //     NavigatorUtil.replace(context, const TabNavigator());
    //   }
    // });

    Timer(Duration(milliseconds: 1500), (){
      if (mobile == null) {
        NavigatorUtil.replace(context, HomePage());
        return;
      }
      bool? isFirstLogin = PreferencesHelper.isFirstLogin(mobile);
      if (isFirstLogin != null) {
        NavigatorUtil.replace(context, HomePage());
        return;
      }

      NetBusiness().hospitalList().then((hospitalValue) {
        if (hospitalValue.data!.length > 1) {
          NetBusiness().doctorInfo().then((value) {
            String hospitalId = value.hospitalId!;
            String hospital = value.hospital!;
            NavigatorUtil.replace(context, SelectHospitalPage(from: 1, hospitalList: hospitalValue.data!, hospitalId: hospitalId, hospital: hospital,));
            PreferencesHelper.setFirstLogin(mobile);
          });
        } else {
          NavigatorUtil.replace(context, HomePage());
        }

      });

    });
  }
}


